<template>
  <div id="userLoginPage">
    <h2 style="margin-bottom: 40px">用户登录</h2>
    <a-form
      style="max-width: 480px; margin: 0 auto"
      label-align="left"
      auto-label-width
      :model="form"
      @submit="handleSubmit"
    >
      <a-form-item class="ant-form-item" field="userAccount" label="账号">
        <a-input v-model="form.userAccount" placeholder="请输入账号" />
      </a-form-item>
      <a-form-item
        class="ant-form-item"
        field="userPassword"
        tooltip="密码不少于 8 位"
        label="密码"
      >
        <a-input-password
          v-model="form.userPassword"
          placeholder="请输入密码"
        />
      </a-form-item>
      <a-form-item>
        <div class="button-container">
          <a-button type="primary" html-type="submit" style="width: 120px">
            登录
          </a-button>
          <a-button type="outline" @click="toUserRegister" style="width: 120px">
            注册
          </a-button>
        </div>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { reactive } from "vue";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";
import { LoginUserStore } from "@/store/user";
import { userLoginUsingPost } from "@/api/userController";
import API from "@/api";

/**
 * 表单信息
 */
const form = reactive({
  userAccount: "",
  userPassword: "",
} as API.UserLoginRequest);

const router = useRouter();
const loginUserStore = LoginUserStore();

/**
 * 提交表单
 * @param data
 */
const handleSubmit = async () => {
  const res = await userLoginUsingPost(form);
  // 登录成功，跳转到主页
  if (res.data.code === 0) {
    await loginUserStore.fetchLoginUser();
    message.success("登录成功");
    await router.push({
      path: "/",
      replace: true,
    });
  } else {
    message.error("登录失败，" + res.data.message);
  }
};
const toUserRegister = () => {
  router.push({
    path: "/user/register",
    replace: true,
  });
};
</script>
<style scoped>
.button-container {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.ant-form-item {
  margin-bottom: 50px; /* 调整这个数值来改变间距大小 */
}
</style>
